using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Read.Api.Application.Command.Pharmacy;
using SmartHealthcare.Read.Api.DTo;

namespace SmartHealthcare.Read.Api.Application.Handler.Pharmacy
{
    /// <summary>
    /// 获取未打单处方列表处理器
    /// </summary>
    public class GetUnprintedPrescriptionsHandler : IRequestHandler<GetUnprintedPrescriptionsCommand, APIResult<List<PrescriptionDto>>>
    {
        private readonly IBaseRepository<Prescription> prescriptionRepository;
        private readonly IBaseRepository<PatientListModel> patientRepository;
        private readonly IBaseRepository<MedicineItem> medicineItemRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetUnprintedPrescriptionsHandler> logger;

        public GetUnprintedPrescriptionsHandler(
            IBaseRepository<Prescription> prescriptionRepository,
            IBaseRepository<PatientListModel> patientRepository,
            IBaseRepository<MedicineItem> medicineItemRepository,
            IMapper mapper,
            ILogger<GetUnprintedPrescriptionsHandler> logger)
        {
            this.prescriptionRepository = prescriptionRepository;
            this.patientRepository = patientRepository;
            this.medicineItemRepository = medicineItemRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<APIResult<List<PrescriptionDto>>> Handle(GetUnprintedPrescriptionsCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<PrescriptionDto>>();

            try
            {
                // 查询未打单的处方（状态为0）
                var query = prescriptionRepository.GetALL()
                    .Where(x => x.State == 0 && x.IsDeleted == false);

                // 应用筛选条件
                if (!string.IsNullOrEmpty(request.RegistrationNumber))
                {
                    query = query.Where(x => x.PatientCode.Contains(request.RegistrationNumber));
                }

                if (!string.IsNullOrEmpty(request.PatientName))
                {
                    // 通过患者姓名筛选需要先获取患者ID
                    var filteredPatientIds = await patientRepository.GetALL()
                        .Where(x => x.Name.Contains(request.PatientName) && x.IsDeleted == false)
                        .Select(x => x.Id)
                        .ToListAsync(cancellationToken);

                    if (filteredPatientIds.Any())
                    {
                        query = query.Where(x => filteredPatientIds.Contains(x.PatientName));
                    }
                    else
                    {
                        // 如果没有找到匹配的患者，返回空列表
                        result.Data = new List<PrescriptionDto>();
                        result.Code = APIEnums.Success;
                        result.Msg = "查询成功";
                        return result;
                    }
                }

                // 获取处方列表
                var prescriptions = await query.ToListAsync(cancellationToken);

                // 获取相关的患者信息
                var patientIds = prescriptions.Select(x => x.PatientName).Distinct().ToList();
                var patients = await patientRepository.GetALL()
                    .Where(x => patientIds.Contains(x.Id) && x.IsDeleted == false)
                    .ToListAsync(cancellationToken);

                // 获取相关的药品明细
                var prescriptionIds = prescriptions.Select(x => x.Id).ToList();
                var medicineItems = await medicineItemRepository.GetALL()
                    .Where(x => prescriptionIds.Contains(x.PrescriptionId) && x.IsDeleted == false)
                    .ToListAsync(cancellationToken);

                // 构建DTO
                var prescriptionDtos = new List<PrescriptionDto>();
                foreach (var prescription in prescriptions)
                {
                    var patient = patients.FirstOrDefault(x => x.Id == prescription.PatientName);
                    var prescriptionDto = mapper.Map<PrescriptionDto>(prescription);

                    if (patient != null)
                    {
                        prescriptionDto.PatientName = patient.Name;
                    }

                    prescriptionDto.StateDescription = GetStateDescription(prescription.State);
                    prescriptionDto.MedicineItems = mapper.Map<List<MedicineItemDto>>(
                        medicineItems.Where(x => x.PrescriptionId == prescription.Id)
                    );

                    prescriptionDtos.Add(prescriptionDto);
                }

                result.Data = prescriptionDtos;
                result.Code = APIEnums.Success;
                result.Msg = "查询成功";

                logger.LogInformation($"查询未打单处方成功，共找到 {prescriptionDtos.Count} 条记录");
            }
            catch (Exception ex)
            {
                result.Code = APIEnums.Error;
                result.Msg = "查询失败：" + ex.Message;
                logger.LogError(ex, "查询未打单处方失败");
            }

            return result;
        }

        private string GetStateDescription(int state)
        {
            return state switch
            {
                0 => "未开单",
                1 => "已开单未发药",
                2 => "已发药",
                _ => "未知状态"
            };
        }
    }
}